﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Runtime.Serialization.Json;
using System.Net;
using System.IO;
using System.Text;
using DHQGHN.PM2.Models;
using System.Dynamic;
using System.Runtime.CompilerServices;
using System.Web.Routing;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;

namespace DHQGHN.PM2.Controllers
{
    [Authorize]
    public class PrintHouseHoldController : BaseController
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(PrintHouseHoldController));
        public ActionResult Index()
        {
            ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
            ViewBag.ActiveMenus[102] = "active";
            ViewBag.ActiveMenus[123] = "active";

            ViewBag.xaCode = MyUser.AdminCode;

            using (WebClient wc = new WebClient())
            {
                Helper.SetHeaderInfo(wc, "GetByID");
                wc.Encoding = Encoding.UTF8;
                //Lấy thông tin xã phường
                AdminisUnitModel UnitModel = new AdminisUnitModel();
                string url, content;
                try
                {
                    url = adminUnitServiceUrl + string.Format("GetByID/{0}", MyUser.AdminID);
                    content = wc.DownloadString(url);
                    UnitModel = JsonConvert.DeserializeObjectAsync<AdminisUnitModel>(content).Result;
                    if (UnitModel == null) UnitModel = new AdminisUnitModel();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                    throw;
                }
                ViewBag.UnitXa = UnitModel;

                //Lấy thông tin huyện/thị xã
                try
                {
                    url = adminUnitServiceUrl + string.Format("GetByID/{0}", UnitModel.P_ID);
                    content = wc.DownloadString(url);
                    UnitModel = JsonConvert.DeserializeObjectAsync<AdminisUnitModel>(content).Result;
                    if (UnitModel == null) UnitModel = new AdminisUnitModel();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                    throw;
                }
                ViewBag.UnitHuyen = UnitModel;

                //Lấy thông tin tỉnh/thành phố
                try
                {
                    url = adminUnitServiceUrl + string.Format("GetByID/{0}", UnitModel.P_ID);
                    content = wc.DownloadString(url);
                    UnitModel = JsonConvert.DeserializeObjectAsync<AdminisUnitModel>(content).Result;
                    if (UnitModel == null) UnitModel = new AdminisUnitModel();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                    throw;
                }
                ViewBag.UnitTinh = UnitModel;
            }

            return View();
        }

        public string getParam(string name, string defaultValue = "")
        {
            string value = Request.Params.Get(name);
            value = value == null || value.Length == 0 ? defaultValue : value;
            return value;
        }

        public void getJsonAdminUnit()
        {
            Response.ClearContent();
            try
            {
                string pcode = getParam("pcode", "0");

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetByPCODE");
                    wc.Encoding = Encoding.UTF8;
                    string url = adminUnitServiceUrl + "GetByPCODE" + "/" + pcode;
                    string content = wc.DownloadString(url);
                    Response.Write(content);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());                
                throw;
            }
        }

        public void getJsonArea()
        {
            Response.ClearContent();
            try
            {
                string UnitCode = getParam("UnitCode", "0");

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetByADMUnitCode");
                    wc.Encoding = Encoding.UTF8;
                    string url = areaServiceUrl + "GetByADMUnitCode" + "/" + UnitCode;
                    string content = wc.DownloadString(url);
                    Response.Write(content);
                }
            }
            catch (Exception e)
            {
                logger.Error(e.ToString());
                Response.Write("[]");
                throw;
            }
        }




        public void getJsonHouseHold()
        {
            Response.ClearContent();
            try
            {
                string area_id = getParam("area_id", "3433912625902");
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetByAreaID");
                    wc.Encoding = Encoding.UTF8;
                    string url = houseHoldServiceUrl + string.Format("GetByAreaID/{0}", area_id);
                    string content = wc.DownloadString(url);
                    Response.Write(content);
                }
            }
            catch (Exception e)
            {
                logger.Error(e.ToString());
                Response.Write("{\"data\":[]}");
                throw;
            }
        }

        public ActionResult printResident0()
        {
            ViewBag.print = getParam("print", "1");
            return View();
        }

        public ActionResult print()
        {
            string houseHoldId = getParam("id", String.Empty);
            ViewBag.print = getParam("print", "1");

            
            using (WebClient wc = new WebClient())
            {
                Helper.SetHeaderInfo(wc, "GetByID");
                wc.Encoding = Encoding.UTF8;

                //Lấy thông tin hộ dân cư
                string url = houseHoldServiceUrl + string.Format("GetByID/{0}", houseHoldId);
                string content = wc.DownloadString(url);
                HouseHoldModel houseHold = JsonConvert.DeserializeObjectAsync<HouseHoldModel>(content).Result;
                if (houseHold == null) houseHold = new HouseHoldModel();

                if (houseHold.HOUSEHOLD_NAME == null)
                    houseHold.HOUSEHOLD_NAME = String.Empty;
                houseHold.HOUSEHOLD_NAME = houseHold.HOUSEHOLD_NAME.ToUpper();

                if (houseHold.HOUSEHOLD_CODE == null)
                    houseHold.HOUSEHOLD_CODE = String.Empty;
                houseHold.HOUSEHOLD_CODE = houseHold.HOUSEHOLD_CODE.ToUpper();
                ViewBag.HouseHold = houseHold;

                //Lấy thông tin địa bàn
                AreaModel area = new AreaModel();
                try
                {
                    url = areaServiceUrl + string.Format("GetByID/{0}", houseHold.AREA_ID);
                    content = wc.DownloadString(url);
                    area = JsonConvert.DeserializeObjectAsync<AreaModel>(content).Result;
                    if (area == null) area = new AreaModel();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                    throw;
                }
                ViewBag.Area = area;

                //Lấy thông tin xã phường
                AdminisUnitModel UnitModel = new AdminisUnitModel();
                try
                {
                    url = adminUnitServiceUrl + string.Format("GetByID/{0}", area.ADM_UNIT_ID);
                    content = wc.DownloadString(url);
                    UnitModel = JsonConvert.DeserializeObjectAsync<AdminisUnitModel>(content).Result;
                    if (UnitModel == null) UnitModel = new AdminisUnitModel();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                }
                ViewBag.UnitXa = UnitModel;

                //Lấy thông tin huyện/thị xã
                try
                {
                    url = adminUnitServiceUrl + string.Format("GetByID/{0}", UnitModel.P_ID);
                    content = wc.DownloadString(url);
                    UnitModel = JsonConvert.DeserializeObjectAsync<AdminisUnitModel>(content).Result;
                    if (UnitModel == null) UnitModel = new AdminisUnitModel();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                    throw;
                }
                ViewBag.UnitHuyen = UnitModel;

                //Lấy thông tin tỉnh/thành phố
                try
                {
                    url = adminUnitServiceUrl + string.Format("GetByID/{0}", UnitModel.P_ID);
                    content = wc.DownloadString(url);
                    UnitModel = JsonConvert.DeserializeObjectAsync<AdminisUnitModel>(content).Result;
                    if (UnitModel == null) UnitModel = new AdminisUnitModel();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                    throw;
                }
                ViewBag.UnitTinh = UnitModel;

                //Lấy thông tin địa chỉ
                AddressModel address = new AddressModel();
                if (houseHold.ADDRESS_ID != null && houseHold.ADDRESS_ID.Length > 0)
                {
                    url = addressServiceUrl + string.Format("GetByID/{0}", houseHold.ADDRESS_ID);
                    content = wc.DownloadString(url);

                    address = JsonConvert.DeserializeObjectAsync<AddressModel>(content).Result;
                    if (address == null) address = new AddressModel();
                }
                ViewBag.Address = address;


                ViewBag.UnitExtNgach = new AdministrativeUnitExtModels();
                ViewBag.UnitExtNgo = new AdministrativeUnitExtModels();
                ViewBag.UnitExtDP = new AdministrativeUnitExtModels();
                ViewBag.Unit0 = new AdministrativeUnitExtModels();
                if (address.ADM_UNIT_EXT_ID != null && address.ADM_UNIT_EXT_ID.Length > 0)
                {
                    AdministrativeUnitExtModels unitExt1 = new AdministrativeUnitExtModels();
                    AdministrativeUnitExtModels unitExt2 = new AdministrativeUnitExtModels();
                    AdministrativeUnitExtModels unitExt3 = new AdministrativeUnitExtModels();
                    //Lấy thông ngõ, ngách ...
                    try
                    {
                        url = adminUnitExtServiceUrl + string.Format("GetByID/{0}", address.ADM_UNIT_EXT_ID);
                        content = wc.DownloadString(url);
                        unitExt1 = JsonConvert.DeserializeObjectAsync<AdministrativeUnitExtModels>(content).Result;
                        if (unitExt1 == null) unitExt1 = new AdministrativeUnitExtModels();
                        ViewBag.Unit0 = unitExt1;

                        url = adminUnitExtServiceUrl + string.Format("GetByID/{0}", unitExt1.PARENT_ID != null && unitExt1.PARENT_ID.Length > 0 ? unitExt1.PARENT_ID : "0");
                        content = wc.DownloadString(url);
                        unitExt2 = JsonConvert.DeserializeObjectAsync<AdministrativeUnitExtModels>(content).Result;
                        if (unitExt2 == null) unitExt2 = new AdministrativeUnitExtModels();

                        url = adminUnitExtServiceUrl + string.Format("GetByID/{0}", unitExt2.PARENT_ID != null && unitExt2.PARENT_ID.Length > 0 ? unitExt2.PARENT_ID : "0");
                        content = wc.DownloadString(url);
                        unitExt3 = JsonConvert.DeserializeObjectAsync<AdministrativeUnitExtModels>(content).Result;
                        if (unitExt3 == null) unitExt3 = new AdministrativeUnitExtModels();
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.ToString());
                        throw;
                    }

                    if (unitExt1.ADM_UNIT_EXT_TYPE == "NGH")
                    {
                        ViewBag.UnitExtNgach = unitExt1;
                        ViewBag.UnitExtNgo = unitExt2;
                        ViewBag.UnitExtDP = unitExt3;
                        ViewBag.Unit0 = new AdministrativeUnitExtModels();
                    }
                    else if (unitExt1.ADM_UNIT_EXT_TYPE == "NG")
                    {
                        ViewBag.UnitExtNgach = new AdministrativeUnitExtModels();
                        ViewBag.UnitExtNgo = unitExt1;
                        ViewBag.UnitExtDP = unitExt2;
                        ViewBag.Unit0 = new AdministrativeUnitExtModels();
                    }
                    else if (unitExt1.ADM_UNIT_EXT_TYPE == "DP")
                    {
                        ViewBag.UnitExtNgach = new AdministrativeUnitExtModels();
                        ViewBag.UnitExtNgo = new AdministrativeUnitExtModels();
                        ViewBag.UnitExtDP = unitExt1;
                        ViewBag.Unit0 = new AdministrativeUnitExtModels();
                    }
                    else
                    {
                        ViewBag.UnitExtNgach = new AdministrativeUnitExtModels();
                        ViewBag.UnitExtNgo = new AdministrativeUnitExtModels();
                        ViewBag.UnitExtDP = new AdministrativeUnitExtModels();
                        ViewBag.Unit0 = unitExt1;
                    }
                }

                Helper.SetHeaderInfo(wc, "GetByHouseHoldIDForPM3");
                //Lấy thông tin công dân
                url = residentServiceUrl + string.Format("/GetByHouseHoldIDForPM3/{0}/0", houseHoldId);
                content = wc.DownloadString(url);
                List<Hashtable> residentList = JsonConvert.DeserializeObjectAsync<List<Hashtable>>(content).Result;
                ViewBag.Resident = residentList;
                ViewBag.ResidentCount = houseHoldId == "0" ? String.Empty : residentList.Count.ToString();


                try
                {
                    string barCode = houseHold.HOUSEHOLD_ID;
                    using (Bitmap bitMap = new Bitmap(barCode.Length * 40, 80))
                    {
                        using (Graphics graphics = Graphics.FromImage(bitMap))
                        {
                            Font oFont = new Font("IDAutomationHC39M", 14);
                            PointF point = new PointF(2f, 2f);
                            SolidBrush blackBrush = new SolidBrush(Color.Black);
                            SolidBrush whiteBrush = new SolidBrush(Color.White);
                            graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
                            graphics.DrawString(barCode, oFont, blackBrush, point);
                        }
                        using (MemoryStream ms = new MemoryStream())
                        {
                            bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                            byte[] byteImage = ms.ToArray();
                            ViewBag.bcode = Convert.ToBase64String(byteImage);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                    throw;
                }
            }



            return View();
        }

        public ActionResult getResidentHtml()
        {
            try
            {
                string houseHoldId = getParam("hid", "-1");
                string residentId = getParam("rid", String.Empty);
                Hashtable a = new Hashtable();
                if (houseHoldId == "-1")
                {
                    Hashtable resident = new Hashtable();
                    resident["DATE_OF_BIRTH"] = String.Empty;
                    resident["FATHER_DOB"] = String.Empty;
                    resident["MOTHER_DOB"] = String.Empty;
                    List<Hashtable> residentList = new List<Hashtable>();
                    residentList.Add(resident);
                    ViewBag.Resident = residentList;
                }
                else
                {
                    using (WebClient wc = new WebClient())
                    {
                        Helper.SetHeaderInfo(wc, "GetByHouseHoldIDForPM3");
                        wc.Encoding = Encoding.UTF8;
                        //Lấy thông tin công dân
                        string url = residentServiceUrl + string.Format("/GetByHouseHoldIDForPM3/{0}/{1}", houseHoldId, residentId);
                        string content = wc.DownloadString(url);
                        List<Hashtable> residentList = JsonConvert.DeserializeObjectAsync<List<Hashtable>>(content).Result;
                        ViewBag.Resident = residentList;
                    }
                }
                return View();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public void updatePrint()
        {
            try
            {
                string houseHoldId = getParam("hid", String.Empty);
                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "Save");
                    wc.Encoding = Encoding.UTF8;
                    string url = houseHoldPrintServiceUrl + string.Format("Save/{0}", houseHoldId);
                    string content = wc.DownloadString(url);
                    Response.Write(content);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public ActionResult Save()
        {
            try
            {
                ViewBag.Title = "Save";

            }
            catch (Exception ee)
            {
                logger.Error(ee);
                throw;
            }
            return null;// RedirectToAction("Index");
        }
    }
}